<template>
  <div class="my-form-item-wrapper">
    <div class="my-form-item">
      <label :for="prop" v-if="label">{{label}}</label>
      <slot></slot>
    </div>
    <span v-if="loadingIcon && isLoading" class="iconfont icon-Loading1 checkLoading"></span>
    <p v-if="errStatus" class="err-msg">{{errMsg}}</p>
  </div>
</template>

<script>
// 导入验证方法
import check from "../../myPlugin/checkout";
export default {
  name: "my-form-item",
  data () {
    return {
      errStatus: false,  //错误状态
      errMsg: "",        //错误提示文字
      isLoading: false,  //loading状态
      timer: null        //定时器
    };
  },
  // 导出验证条件
  provide () {
    return {
      mode: this.form.rules[this.prop]
    };
  },
  // 接收myform的数据
  inject: ["form"],
  props: {
    prop: {
      type: String
    },
    label: { // 输入框前文字
      type: String,
      default: ""
    },
    loadingIcon: { // 是都显示检测loading图标
      type: Boolean,
      default: true
    }
  },
  methods: {
    // checkout(rules) {
    //     rules.forEach(ele => {
    //         window.console.log(ele)
    //     })
    // },
    // 验证函数
    validate (index) {
      this.errMsg = "";
      clearTimeout(this.timer)
      this.isLoading = true
      this.timer = setTimeout(() => { //这里只是一个模拟  感觉错误提示突然出现有点突兀
        this.form.rules[this.prop].forEach((ele, i) => {
          if (i === index) {
            // 调用检测函数得到结果
            let flog = check.checkInit(ele, this.form.model[this.prop])
            window.console.log(flog, this.form.rules)
            // 更新错误状态
            this.errStatus = !flog
            // 更新错误提示文字
            this.errMsg = this.form.rules[this.prop][index].message
            // 关闭loading图标
            this.isLoading = false
          }
        });
      }, 500)
    }
  },
  mounted () {
    this.$on("validate", this.validate)
  }
};
</script>

<style scoped>
.my-form-item-wrapper {
  position: relative;
  font-size: 14px;
  display: flex;
  flex-direction: column;
  width: 100%;
}
.my-form-item-wrapper .my-form-item {
  position: relative;
  display: flex;
  align-items: center;
  width: 100%;
}
.my-form-item-wrapper label {
  display: inline-block;
  padding-right: 0.15rem;
  font-size: 0.32rem;
  flex: 2;
  white-space: nowrap;
  overflow: hidden;
}
.my-form-item-wrapper .err-msg {
  box-sizing: border-box;
  padding-left: 1.8rem;
  padding-top: 0.1rem;
  color: lightcoral;
}
.my-form-item-wrapper .checkLoading {
  position: absolute;
  right: 0.2rem;
  color: darkcyan;
  font-size: 0.4rem;
  height: 0.5rem;
  width: 0.5rem;
  line-height: 0.5rem;
  text-align: center;
  margin-top: -0.25rem;
  top: 50%;
  animation: loading1 1s linear infinite;
}
@keyframes loading1 {
  0% {
    transform: rotateZ(0deg);
  }
  100% {
    transform: rotateZ(360deg);
  }
}
</style>
